package syn;

public class BuyTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket,"you").start();
        new Thread(ticket,"me").start();
        new Thread(ticket,"others").start();
    }
}

class Ticket implements Runnable{

    // ticket and flag
    private int ticket=10;
    private boolean flag=true;

    @Override
    public void run() {
        while(flag){
            try {
                buy();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public synchronized void buy() throws InterruptedException {
        if(ticket<=0){
            flag=false;
            return;
        }
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName()+"拿到第 "+ticket--+" 张票");
    }
}